package org.cmy.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api")
public class TestController {

    @GetMapping("/public/hello")
    public String publicHello() {
        return "Hello, public!";
    }

    @GetMapping("/user/profile")
    @PreAuthorize("hasAuthority('user:read')")
    public String userProfile(Authentication auth) {
        return "User profile: " + auth.getName() + ", Authorities: " + auth.getAuthorities();
    }

    @GetMapping("/admin/delete")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminDelete() {
        return "Deleted by admin!";
    }

    @GetMapping("/token-info")
    public ResponseEntity<?> getTokenInfo(@AuthenticationPrincipal Jwt jwt) {
        try {
            Map<String,String> map = new HashMap<>();
            map.put("subject",jwt.getSubject());
            map.put("expiresAt", jwt.getSubject());
            map.put("authorities", String.join(",", jwt.getClaimAsStringList("authorities")));
            map.put("scopes", String.join(",",jwt.getClaimAsStringList("scope")));

            return ResponseEntity.ok(map);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body("");
        }
    }
}